package com.winning.core.controller;

import java.io.IOException;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.apache.log4j.Logger;
import org.springframework.http.MediaType;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import com.framework.context.SysConfig;
import com.framework.helper.SpringContextHelper;
import com.framework.server.json.JSONArray;
import com.framework.util.date.DateConvert;
import com.winning.common.Constans;
import com.winning.common.tools.CommonTool;
import com.winning.core.service.inter.LoginManagerServiceInter;

/**
 * 类名称：LoginControl
 * 类描述：登录流程
 * 创建人：liuwensheng
 * 创建时间：2015-3-2 下午4:19:26
 * 修改人：liuwensheng
 * 修改时间：2015-3-2 下午4:19:26
 * 修改备注：   js_1869
 */
@Controller
@RequestMapping("/loginControl")
public class LoginControl {
    private static Logger LOGGER = Logger.getLogger(Constans.LOG4J_PBS_LOGGER_ID);

    /**
     * @param @param  username
     * @param @param  password
     * @param @param  cdflMap
     * @param @return
     * @return String
     * @throws SQLException
     * @throws IOException
     * @throws ServletException
     * @throws
     * @Title: doLoginHandler
     * @Description: 用户登录接口，返回菜单信息列表, 必须是POST方法请求，否则无法接受请求
     */
    @RequestMapping(value = "/toDoLogin", method = RequestMethod.POST)
    public String doLoginHandler(HttpSession session, HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException, SQLException {
        String clientIP = CommonTool.getIpAddr(req);

        LOGGER.info("--> Login request user client IP:" + clientIP);

        LoginManagerServiceInter loginManagerServiceInter = (LoginManagerServiceInter) SpringContextHelper.getBean(Constans.USER_LOGIN_SERVICE);

        //密码是否加密控制参数,1：加密；0：不加密。参数维护在表SYS_XTCS里面
        String setCode = SysConfig.getInstance().getConfig("plat.login.setCode");

        String username = req.getParameter("kh");
        String password = req.getParameter("mm");

        LOGGER.info("--> Login username:" + username);

        //解密登录界面login.jsp中对用户名和密码的加密
		/*username = new String(Base64.decode(username), "UTF-8");
		password = new String(Base64.decode(password), "UTF-8");

		if("1".equals(setCode))
		{
			password = SHA1.getSHA(password);
		}
		
		LOGGER.info("--> Login setCode:" + setCode);*/

        //1、登录验证
        Map<String, Object> userInfoMap = loginManagerServiceInter.userLogin(username, password);

        String jgdm = "";
        String rygh = "";
        String ryxm = "";

        try {
            if ("true".equals(userInfoMap.get("status"))) {
                jgdm = (String) userInfoMap.get("jgbm");
                session.setAttribute("jgbm", jgdm);

                session.setAttribute("jgmc", (String) userInfoMap.get("jgmc"));
                session.setAttribute("jgjc", (String) userInfoMap.get("jgjc"));
                session.setAttribute("gxqy", (String) userInfoMap.get("gxqy"));
                session.setAttribute("jgjb", (String) userInfoMap.get("jgjb"));
                session.setAttribute("jglb", (String) userInfoMap.get("jglb"));

                ryxm = (String) userInfoMap.get("ryxm");
                session.setAttribute("ryxm", ryxm);

                rygh = (String) userInfoMap.get("rybm");
                session.setAttribute("rybm", rygh);
                session.setAttribute("zclsh", (String) userInfoMap.get("zclsh"));
                session.setAttribute("jsmc", (String) userInfoMap.get("jsmc"));
                session.setAttribute("dlsj", DateConvert.getNowYYYY_MM_DD_HH_MM_DD());
                session.setAttribute("dldm", username);

                if ("1".equals(setCode)) {
                    session.setAttribute("dlmm", password);
                } else {
                    session.setAttribute("dlmm", password);
                }

                //判断密码是否过期, 参数维护在表SYS_XTCS里面
                int day = Integer.valueOf(SysConfig.getInstance().getConfig("sjhy_password_duration_value") == null ? "0" : SysConfig.getInstance().getConfig("sjhy_password_duration_value"));

                LOGGER.info("--> Login password duration day:" + day);
				
				/*if(day > 0)
				{
					//获取当前请求线程对应的数据库产品名称
					String dbName = DBInfoManager.getDBInfo();

					if(WebConstant.SQLSERVER_DB.equals(dbName))
					{
						int dayOffset = Integer.parseInt((String) userInfoMap.get("dayOffset"));
						if(dayOffset>day)
						{
							session.setAttribute("pwd", "true");
						}
						else
						{
							session.setAttribute("pwd", "false");
						}
					}
				}
				else
				{
					session.setAttribute("pwd", "false");
				}*/

                //是否开启密码强度验证, 参数维护在表SYS_XTCS里面
                String strongPasswordValue = SysConfig.getInstance().getConfig("sjhy_strong_password_value");

                session.setAttribute("spwd", strongPasswordValue);

                LOGGER.info("--> Login strong password:" + strongPasswordValue);

                //登录日志,登陆结果 T：成功；F:失败
                //saveLogHandler(jgdm, rygh, dldm, dlmm, clientIP, ryxm, "JCPT", "T");
            } else {
                req.setAttribute("msg", userInfoMap.get("msg"));

                //登录日志
                //saveLogHandler(jgdm, rygh, dldm, dlmm, clientIP, ryxm, "JCPT", "F");
                return "toLoginView";
            }
        } catch (Exception e) {
            e.printStackTrace();
            req.setAttribute("msg", "该用户没有操作权限，请与管理员联系。");

            //登录日志
            //saveLogHandler(jgdm, rygh, dldm, dlmm, clientIP, ryxm, "JCPT", "F");

            return "toLoginView";
        }
        //session.setAttribute("ryxm", "周瑛");
        return "toMainJsp";
    }

    /**
     * 获取登录用户信息
     *
     * @param req
     * @param resp
     * @return
     * @throws JSONException
     * @throws IOException
     */
    @RequestMapping(value = "/getUserInfo", method = RequestMethod.POST)
    public @ResponseBody
    String getUserInfoHandler(HttpServletRequest req, HttpServletResponse resp) throws IOException {
        HttpSession session = req.getSession();

        //获取当前用户
        String ryxm = (String) session.getAttribute("ryxm");
        //获取机构名称
        String jgmc = (String) session.getAttribute("jgmc");
        //获取机构权限
        String jsmc = (String) session.getAttribute("jsmc");
        //获取登录时间
        String dlsj = (String) session.getAttribute("dlsj");

        //JSONObject jsonObject = new JSONObject();

        //jsonObject.put("ryxm", ryxm);
        //jsonObject.put("jgmc", jgmc);
        //jsonObject.put("jsmc", jsmc);
        //jsonObject.put("dlsj", dlsj);

        return null;
    }

    /**
     * 获取一级菜单信息
     *
     * @param request
     * @param response
     * @throws JSONException
     * @throws IOException
     * @throws com.framework.server.json.JSONException
     */
    @RequestMapping(value = "/getFirstMenuList", method = RequestMethod.POST)
    public @ResponseBody
    String getFirstMenuListHandler(HttpServletRequest request, HttpServletResponse response) throws IOException, com.framework.server.json.JSONException {
        //以下部分 从session 中获取
        HttpSession session = request.getSession();
        String zclsh = (String) session.getAttribute("zclsh");
        String jgbm = (String) session.getAttribute("jgbm");

        //获取请求参数
        String queryParamList = request.getParameter("queryParamList");
        com.framework.server.json.JSONObject urlJson = new com.framework.server.json.JSONObject(queryParamList);

        //获取前台中的一级菜单代码 用于查询 二、三级菜单
        String sjcddm = urlJson.getString("sjcddm");

        Map<String, Object> paramsMap = new HashMap<String, Object>();

        paramsMap = new HashMap<String, Object>();
        paramsMap.put("sjcddm", sjcddm);
        paramsMap.put("zclsh", zclsh);
        paramsMap.put("yljgdm", jgbm);

        LoginManagerServiceInter loginManagerServiceInter = (LoginManagerServiceInter) SpringContextHelper.getBean(Constans.USER_LOGIN_SERVICE);

        //查询一级菜单
        JSONArray firstMenuJsonArray = loginManagerServiceInter.getFirstMenuListHandler(paramsMap);

        LOGGER.info("--> First menu json data list:" + firstMenuJsonArray.toString());

        //将菜单JSON数据返回给界面
        return firstMenuJsonArray.toString();
    }

    /**
     * 获取二三级子菜单列表
     *
     * @param request
     * @param response
     * @throws JSONException
     * @throws IOException
     * @throws com.framework.server.json.JSONException
     */
    @RequestMapping(value = "/getOtherMenuList", method = RequestMethod.POST)
    public @ResponseBody
    String getOtherMenuListHandler(HttpServletRequest request, HttpServletResponse response) throws IOException, com.framework.server.json.JSONException {
        //以下部分 从session 中获取
        HttpSession session = request.getSession();
        String zclsh = (String) session.getAttribute("zclsh");
        String jgbm = (String) session.getAttribute("jgbm");
        String urlParams = (String) session.getAttribute("urlParams");

        //获取请求参数
        String queryParamList = request.getParameter("queryParamList");
        com.framework.server.json.JSONObject urlJson = new com.framework.server.json.JSONObject(queryParamList);

        //获取前台中的一级菜单代码 用于查询 二、三级菜单
        String sjcddm = urlJson.getString("sjcddm");

        LoginManagerServiceInter loginManagerServiceInter = (LoginManagerServiceInter) SpringContextHelper.getBean(Constans.USER_LOGIN_SERVICE);

        Map<String, Object> paramsMap = new HashMap<String, Object>();

        paramsMap = new HashMap<String, Object>();
        paramsMap.put("sjcddm", sjcddm);
        paramsMap.put("zclsh", zclsh);
        paramsMap.put("yljgdm", jgbm);

        JSONArray secondMenuList = loginManagerServiceInter.getSecondMenuListHandler(paramsMap, urlParams, zclsh, jgbm);

        LOGGER.info("--> First menu json data list:" + secondMenuList.toString());

        //将菜单JSON数据返回给界面
        return secondMenuList.toString();
    }

    /**
     * @param @param  username
     * @param @return
     * @return String
     * @throws IOException
     * @throws
     * @Title: userLoginOutHandler
     * @Description: 用户退出登录
     */
    @RequestMapping("/toDoLoginOut")
    public void userLoginOutHandler(@RequestParam("username") String username, HttpSession session, HttpServletRequest req, HttpServletResponse resp) throws IOException {
        //session失效
        session.invalidate();

        //重定向到登录界面
        resp.sendRedirect("/bifx/html/frame_style/login.html");
    }

    /**
     * @param @param  username
     * @param @param  session
     * @param @param  req
     * @param @param  resp
     * @param @throws IOException
     * @return void
     * @throws
     * @Title: userResetHandler
     * @Description: 用户注销流程
     */
    @RequestMapping("/toDoRest")
    public void userResetHandler(@RequestParam("username") String username, HttpSession session, HttpServletRequest req, HttpServletResponse resp) throws IOException {
        //session失效
        //session.invalidate();

        //重定向到登录界面
        resp.sendRedirect("/bifx/html/frame_style/login.html");
    }


    /**
     * @param @param yljgdm 医疗机构代码
     * @param @param rygh   人员工号
     * @param @param dldm   登录代码
     * @param @param dlmm   登录密码
     * @param @param ip     IP
     * @param @param xm     姓名
     * @param @param ssxt   所属系统
     * @param @param dljg   登录结果
     * @return void
     * @throws
     * @Title: saveLogHandler
     * @Description: 增加记录访问子业务系统日志接口
     */
    private void saveLogHandler(String yljgdm, String rygh, String dldm, String dlmm, String ip, String xm, String ssxt, String dljg) {
        CommonTool.saveLogHandler(yljgdm, rygh, dldm, dlmm, ip, xm, ssxt, dljg);
    }

}
